ibm-watson-machine-learning¶This notebook contains the steps and code to demonstrate support of AutoAI experiments in Watson Machine Learning service. It introduces commands for data retrieval, training experiments, persisting pipelines, testing pipelines, refining pipelines, and scoring.
Some familiarity with Python is helpful. This notebook uses Python 3.8.
The learning goals of this notebook are:
This notebook contains the following parts:
Before you use the sample code in this notebook, you must perform the following setup tasks:
Authenticate the Watson Machine Learning service on IBM Cloud. You need to provide Cloud API key and location.
Tip: Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below. You can also get a service specific url by going to the Endpoint URLs section of the Watson Machine Learning docs. You can check your instance location in your Watson Machine Learning (WML) Service instance details.
You can use IBM Cloud CLI to retrieve the instance location.
ibmcloud login --apikey API_KEY -a https://cloud.ibm.com
ibmcloud resource service-instance WML_INSTANCE_NAME
NOTE: You can also get a service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, and then copy the created key and paste it in the following cell.
Action: Enter your api_key and location in the following cell.
api_key = 'PUT_YOUR_KEY_HERE'
location = 'us-south'
wml_credentials = {
"apikey": api_key,
"url": 'https://' + location + '.ml.cloud.ibm.com'
}
!pip install -U ibm-watson-machine-learning | tail -n 1
!pip install -U autoai-libs | tail -n 1
!pip install -U scikit-learn==0.23.1 | tail -n 1
!pip install wget | tail -n 1
!pip install matplotlib | tail -n 1
from ibm_watson_machine_learning import APIClient
client = APIClient(wml_credentials)
You need to create a space that will be used for your work. If you do not have a space, you can use Deployment Spaces Dashboard to create one.
space_id and paste it belowTip: You can also use SDK to prepare the space for your work. More information can be found here.
Action: assign space ID below
space_id = 'PASTE YOUR SPACE ID HERE'
You can use the list method to print all existing spaces.
client.spaces.list(limit=10)
To be able to interact with all resources available in Watson Machine Learning, you need to set the space which you will be using.
client.set.default_space(space_id)
'SUCCESS'
In next cell we read the COS credentials from the space.
cos_credentials = client.spaces.get_details(space_id=space_id)['entity']['storage']['properties']
Define connection information to COS bucket and training data CSV file. This example uses the German Credit Risk dataset.
The code in next cell uploads training data to the bucket.
filename = 'credit_risk_training_light.csv'
datasource_name = 'bluemixcloudobjectstorage'
bucketname = cos_credentials['bucket_name']
Download training data from git repository.
import os, wget
url = 'https://raw.githubusercontent.com/IBM/watson-machine-learning-samples/master/cloud/data/credit_risk/credit_risk_training_light.csv'
if not os.path.isfile(filename): wget.download(url)
conn_meta_props= {
client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {datasource_name} ",
client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(datasource_name),
client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
client.connections.ConfigurationMetaNames.PROPERTIES: {
'bucket': bucketname,
'access_key': cos_credentials['credentials']['editor']['access_key_id'],
'secret_key': cos_credentials['credentials']['editor']['secret_access_key'],
'iam_url': 'https://iam.cloud.ibm.com/identity/token',
'url': cos_credentials['endpoint_url']
}
}
conn_details = client.connections.create(meta_props=conn_meta_props)
Note: The above connection can be initialized alternatively with api_key and resource_instance_id.
The above cell can be replaced with:
conn_meta_props= {
client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ",
client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(db_name),
client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
client.connections.ConfigurationMetaNames.PROPERTIES: {
'bucket': bucket_name,
'api_key': cos_credentials['apikey'],
'resource_instance_id': cos_credentials['resource_instance_id'],
'iam_url': 'https://iam.cloud.ibm.com/identity/token',
'url': 'https://s3.us.cloud-object-storage.appdomain.cloud'
}
}
conn_details = client.connections.create(meta_props=conn_meta_props)
connection_id = client.connections.get_uid(conn_details)
Define connection information to training data.
from ibm_watson_machine_learning.helpers import DataConnection, S3Location
credit_risk_conn = DataConnection(
connection_asset_id=connection_id,
location=S3Location(bucket=bucketname,
path=filename))
training_data_reference=[credit_risk_conn]
Check the connection information. Upload the data and validate.
credit_risk_conn._wml_client = client
credit_risk_conn.write(data=filename, remote_name=filename)
credit_risk_conn.read()
| CheckingStatus | LoanDuration | CreditHistory | LoanPurpose | LoanAmount | ExistingSavings | EmploymentDuration | InstallmentPercent | Sex | OthersOnLoan | ... | OwnsProperty | Age | InstallmentPlans | Housing | ExistingCreditsCount | Job | Dependents | Telephone | ForeignWorker | Risk | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 0_to_200 | 31 | credits_paid_to_date | other | 1889 | 100_to_500 | less_1 | 3 | female | none | ... | savings_insurance | 32 | none | own | 1 | skilled | 1 | none | yes | No Risk |
| 1 | less_0 | 18 | credits_paid_to_date | car_new | 462 | less_100 | 1_to_4 | 2 | female | none | ... | savings_insurance | 37 | stores | own | 2 | skilled | 1 | none | yes | No Risk |
| 2 | less_0 | 15 | prior_payments_delayed | furniture | 250 | less_100 | 1_to_4 | 2 | male | none | ... | real_estate | 28 | none | own | 2 | skilled | 1 | yes | no | No Risk |
| 3 | 0_to_200 | 28 | credits_paid_to_date | retraining | 3693 | less_100 | greater_7 | 3 | male | none | ... | savings_insurance | 32 | none | own | 1 | skilled | 1 | none | yes | No Risk |
| 4 | no_checking | 28 | prior_payments_delayed | education | 6235 | 500_to_1000 | greater_7 | 3 | male | none | ... | unknown | 57 | none | own | 2 | skilled | 1 | none | yes | Risk |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 244 | 0_to_200 | 22 | credits_paid_to_date | repairs | 812 | less_100 | 4_to_7 | 3 | male | none | ... | savings_insurance | 19 | bank | rent | 1 | unemployed | 1 | none | yes | No Risk |
| 245 | 0_to_200 | 13 | prior_payments_delayed | furniture | 2735 | 500_to_1000 | 4_to_7 | 2 | female | none | ... | savings_insurance | 45 | stores | rent | 2 | skilled | 1 | none | yes | Risk |
| 246 | less_0 | 28 | credits_paid_to_date | radio_tv | 530 | less_100 | 1_to_4 | 2 | male | none | ... | real_estate | 32 | stores | own | 1 | skilled | 1 | none | yes | No Risk |
| 247 | less_0 | 17 | credits_paid_to_date | retraining | 2119 | less_100 | 1_to_4 | 3 | female | none | ... | savings_insurance | 23 | bank | rent | 1 | unskilled | 1 | none | yes | No Risk |
| 248 | no_checking | 26 | outstanding_credit | furniture | 3573 | greater_1000 | greater_7 | 5 | male | none | ... | car_other | 39 | none | own | 2 | skilled | 1 | none | yes | Risk |
249 rows × 21 columns
Provide the input information for AutoAI optimizer:
name - experiment nameprediction_type - type of the problemprediction_column - target column namescoring - optimization metricfrom ibm_watson_machine_learning.experiment import AutoAI
experiment = AutoAI(wml_credentials, space_id=space_id)
pipeline_optimizer = experiment.optimizer(
name='Credit Risk Prediction - AutoAI',
prediction_type=AutoAI.PredictionType.BINARY,
prediction_column='Risk',
scoring=AutoAI.Metrics.ROC_AUC_SCORE,
)
Configuration parameters can be retrieved via get_params().
pipeline_optimizer.get_params()
{'name': 'Credit Risk Prediction - AutoAI',
'desc': '',
'prediction_type': 'binary',
'prediction_column': 'Risk',
'prediction_columns': None,
'timestamp_column_name': None,
'scoring': 'roc_auc',
'holdout_size': 0.1,
'max_num_daub_ensembles': 2,
't_shirt_size': 'l',
'train_sample_rows_test_size': None,
'include_only_estimators': None,
'backtest_num': None,
'lookback_window': None,
'forecast_window': None,
'backtest_gap_length': None,
'cognito_transform_names': None,
'data_join_graph': False,
'csv_separator': ',',
'excel_sheet': 0,
'encoding': 'utf-8',
'positive_label': None,
'drop_duplicates': True,
'text_processing': None,
'word2vec_feature_number': None,
'run_id': None}
Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.
run_details = pipeline_optimizer.fit(
training_data_reference=training_data_reference,
background_mode=False)
Training job f7834f0a-495f-40a2-bb17-5702c7905898 completed: 100%|████████| [02:27<00:00, 1.47s/it]
You can use the get_run_status() method to monitor AutoAI jobs in background mode.
pipeline_optimizer.get_run_status()
'completed'
You can list trained pipelines and evaluation metrics information in
the form of a Pandas DataFrame by calling the summary() method. You can
use the DataFrame to compare all discovered pipelines and select the one
you like for further testing.
summary = pipeline_optimizer.summary()
summary
| Enhancements | Estimator | training_roc_auc_(optimized) | holdout_precision | training_average_precision | holdout_average_precision | training_log_loss | holdout_recall | training_precision | holdout_accuracy | holdout_balanced_accuracy | training_recall | holdout_f1 | holdout_log_loss | training_accuracy | holdout_roc_auc | training_balanced_accuracy | training_f1 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Pipeline Name | ||||||||||||||||||
| Pipeline_4 | HPO, FE | ExtraTreesClassifierEstimator | 0.865220 | 0.500000 | 0.735040 | 0.787642 | 0.572779 | 0.625 | 0.640468 | 0.68 | 0.665441 | 0.705534 | 0.555556 | 0.599626 | 0.790210 | 0.786765 | 0.766228 | 0.671202 |
| Pipeline_3 | HPO, FE | ExtraTreesClassifierEstimator | 0.864422 | 0.500000 | 0.735772 | 0.749285 | 0.587914 | 0.625 | 0.635092 | 0.68 | 0.665441 | 0.735837 | 0.555556 | 0.605596 | 0.790270 | 0.772059 | 0.774970 | 0.681373 |
| Pipeline_2 | HPO | ExtraTreesClassifierEstimator | 0.853007 | 0.555556 | 0.733979 | 0.715756 | 0.587513 | 0.625 | 0.589803 | 0.72 | 0.694853 | 0.735178 | 0.588235 | 0.611750 | 0.763243 | 0.750000 | 0.755409 | 0.653585 |
| Pipeline_8 | HPO, FE | XGBClassifierEstimator | 0.847560 | 0.545455 | 0.700351 | 0.752966 | 0.463176 | 0.750 | 0.668974 | 0.72 | 0.727941 | 0.691041 | 0.631579 | 0.644512 | 0.799279 | 0.764706 | 0.768597 | 0.678288 |
| Pipeline_6 | HPO | XGBClassifierEstimator | 0.836576 | 0.625000 | 0.695192 | 0.734206 | 0.503487 | 0.625 | 0.650051 | 0.76 | 0.724265 | 0.676548 | 0.625000 | 0.722906 | 0.790270 | 0.727941 | 0.758146 | 0.662852 |
| Pipeline_7 | HPO, FE | XGBClassifierEstimator | 0.836576 | 0.625000 | 0.695192 | 0.734206 | 0.503487 | 0.625 | 0.650051 | 0.76 | 0.724265 | 0.676548 | 0.625000 | 0.722906 | 0.790270 | 0.727941 | 0.758146 | 0.662852 |
| Pipeline_1 | ExtraTreesClassifierEstimator | 0.828133 | 0.666667 | 0.684145 | 0.538938 | 0.587499 | 0.500 | 0.768727 | 0.76 | 0.691176 | 0.454545 | 0.571429 | 0.559774 | 0.785766 | 0.750000 | 0.692016 | 0.560717 | |
| Pipeline_5 | XGBClassifierEstimator | 0.826340 | 0.500000 | 0.648397 | 0.735952 | 0.536144 | 0.500 | 0.630541 | 0.68 | 0.632353 | 0.646245 | 0.500000 | 0.599333 | 0.776757 | 0.750000 | 0.739789 | 0.637516 |
You can visualize the scoring metric calculated on a holdout data set.
import pandas as pd
pd.options.plotting.backend = "plotly"
summary.holdout_roc_auc.plot()
Download and reconstruct a scikit-learn pipeline model object from the AutoAI training job.
best_pipeline = pipeline_optimizer.get_pipeline()
Check confusion matrix for selected pipeline.
pipeline_optimizer.get_pipeline_details()['confusion_matrix']
| fn | fp | tn | tp | |
|---|---|---|---|---|
| true_class | ||||
| No Risk | 5 | 3 | 5 | 12 |
| Risk | 3 | 5 | 12 | 5 |
Check features importance for selected pipeline.
pipeline_optimizer.get_pipeline_details()['features_importance']
| features_importance | |
|---|---|
| Age | 1.00 |
| LoanAmount | 0.25 |
| CurrentResidenceDuration | 0.23 |
| CreditHistory | 0.22 |
| LoanPurpose | 0.21 |
| OthersOnLoan | 0.21 |
| Dependents | 0.21 |
| ExistingSavings | 0.19 |
| LoanDuration | 0.16 |
| InstallmentPlans | 0.14 |
| CheckingStatus | 0.14 |
| OwnsProperty | 0.13 |
| EmploymentDuration | 0.12 |
| Job | 0.10 |
| ExistingCreditsCount | 0.10 |
| Sex | 0.10 |
| InstallmentPercent | 0.08 |
| Housing | 0.07 |
| ForeignWorker | 0.00 |
| Telephone | 0.00 |
from ibm_watson_machine_learning.helpers import pipeline_to_script
pipeline_to_script(best_pipeline)
best_pipeline.visualize()
Each node in the visualization is a machine-learning operator (transformer or estimator). Each edge indicates data flow (transformed output from one operator becomes input to the next). The input to the root nodes is the initial dataset and the output from the sink node is the final prediction. When you hover the mouse pointer over a node, a tooltip shows you the configuration arguments of the corresponding operator (tuned hyperparameters). When you click on the hyperlink of a node, it brings you to a documentation page for the operator.
best_pipeline.pretty_print(ipython_display=True, astype='sklearn')
In the pretty-printed code, >> is the pipe combinator (dataflow
edge) and & is the and combinator (combining multiple subpipelines).
They correspond to the make_pipeline and make_union functions from
scikit-learn, respectively. If you prefer the functions, you can
instead pretty-print your pipeline with
best_pipeline.pretty_print(ipython_display=True, combinators=False).
train_df = pipeline_optimizer.get_data_connections()[0].read()
train_X = train_df.drop(['Risk'], axis=1).values
train_y = train_df.Risk.values
predicted_y = best_pipeline.predict(train_X)
predicted_y[:5]
array(['No Risk', 'No Risk', 'No Risk', 'No Risk', 'Risk'], dtype=object)
To list historical runs use method list().
Note: You can filter runs by providing experiment name.
experiment.runs(filter='Credit Risk Prediction - AutoAI').list()
To work with historical pipelines found during a particular optimizer
run, you need to first provide the run_id to select the fitted
optimizer.
Note: you can assign selected run_id to the run_id variable.
run_id = run_details['metadata']['id']
experiment.runs.get_params(run_id=run_id)
{'name': 'Credit Risk Prediction - AutoAI',
'desc': '',
'prediction_type': 'binary',
'prediction_column': 'Risk',
'prediction_columns': None,
'timestamp_column_name': None,
'holdout_size': 0.1,
'max_num_daub_ensembles': 2.0,
't_shirt_size': 'a6c4923b-b8e4-444c-9f43-8a7ec3020110',
'include_only_estimators': None,
'cognito_transform_names': None,
'train_sample_rows_test_size': None,
'csv_separator': ',',
'excel_sheet': 0,
'encoding': 'utf-8'}
historical_opt = experiment.runs.get_optimizer(run_id)
run_details = historical_opt.get_run_details()
historical_opt.summary()
| Enhancements | Estimator | training_roc_auc | holdout_precision | training_average_precision | holdout_average_precision | training_log_loss | holdout_recall | training_precision | holdout_accuracy | holdout_balanced_accuracy | training_recall | holdout_f1 | holdout_log_loss | training_accuracy | holdout_roc_auc | training_balanced_accuracy | training_f1 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Pipeline Name | ||||||||||||||||||
| Pipeline_1 | ExtraTreesClassifierEstimator | 0.828133 | 0.666667 | 0.684145 | 0.538938 | 0.587499 | 0.500 | 0.768727 | 0.76 | 0.691176 | 0.454545 | 0.571429 | 0.559774 | 0.785766 | 0.750000 | 0.692016 | 0.560717 | |
| Pipeline_2 | HPO | ExtraTreesClassifierEstimator | 0.853007 | 0.555556 | 0.733979 | 0.715756 | 0.587513 | 0.625 | 0.589803 | 0.72 | 0.694853 | 0.735178 | 0.588235 | 0.611750 | 0.763243 | 0.750000 | 0.755409 | 0.653585 |
| Pipeline_3 | HPO, FE | ExtraTreesClassifierEstimator | 0.864422 | 0.500000 | 0.735772 | 0.749285 | 0.587914 | 0.625 | 0.635092 | 0.68 | 0.665441 | 0.735837 | 0.555556 | 0.605596 | 0.790270 | 0.772059 | 0.774970 | 0.681373 |
| Pipeline_4 | HPO, FE | ExtraTreesClassifierEstimator | 0.865220 | 0.500000 | 0.735040 | 0.787642 | 0.572779 | 0.625 | 0.640468 | 0.68 | 0.665441 | 0.705534 | 0.555556 | 0.599626 | 0.790210 | 0.786765 | 0.766228 | 0.671202 |
| Pipeline_5 | XGBClassifierEstimator | 0.826340 | 0.500000 | 0.648397 | 0.735952 | 0.536144 | 0.500 | 0.630541 | 0.68 | 0.632353 | 0.646245 | 0.500000 | 0.599333 | 0.776757 | 0.750000 | 0.739789 | 0.637516 | |
| Pipeline_6 | HPO | XGBClassifierEstimator | 0.836576 | 0.625000 | 0.695192 | 0.734206 | 0.503487 | 0.625 | 0.650051 | 0.76 | 0.724265 | 0.676548 | 0.625000 | 0.722906 | 0.790270 | 0.727941 | 0.758146 | 0.662852 |
| Pipeline_7 | HPO, FE | XGBClassifierEstimator | 0.836576 | 0.625000 | 0.695192 | 0.734206 | 0.503487 | 0.625 | 0.650051 | 0.76 | 0.724265 | 0.676548 | 0.625000 | 0.722906 | 0.790270 | 0.727941 | 0.758146 | 0.662852 |
| Pipeline_8 | HPO, FE | XGBClassifierEstimator | 0.847560 | 0.545455 | 0.700351 | 0.752966 | 0.463176 | 0.750 | 0.668974 | 0.72 | 0.727941 | 0.691041 | 0.631579 | 0.644512 | 0.799279 | 0.764706 | 0.768597 | 0.678288 |
hist_pipeline = historical_opt.get_pipeline(pipeline_name='Pipeline_3')
predicted_y = hist_pipeline.predict(train_X)
predicted_y[:5]
array(['No Risk', 'No Risk', 'No Risk', 'No Risk', 'Risk'], dtype=object)
In this section you learn how to refine and retrain the best
pipeline returned by AutoAI. There are many ways to refine a pipeline.
For illustration, simply replace the final estimator in the
pipeline by an interpretable model. The call to
wrap_imported_operators() augments scikit-learn operators with
schemas for hyperparameter tuning.
from sklearn.linear_model import LogisticRegression as LR
from sklearn.tree import DecisionTreeClassifier as Tree
from sklearn.neighbors import KNeighborsClassifier as KNN
from lale.lib.lale import Hyperopt
from lale import wrap_imported_operators
wrap_imported_operators()
Start by removing the last step of the pipeline, i.e., the final estimator.
prefix = hist_pipeline.remove_last().freeze_trainable()
prefix.visualize()
Next, add a new final step, which consists of a choice of three
estimators. In this code, | is the or combinator (algorithmic
choice). It defines a search space for another optimizer run.
new_pipeline = prefix >> (LR | Tree | KNN)
new_pipeline.visualize()
Hyperopt configuration and training¶To automatically select the algorithm and tune its hyperparameters, we
create an instance of the Hyperopt optimizer and fit it to the
data.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(train_X, train_y, test_size=0.15, random_state=33)
hyperopt = Hyperopt(estimator=new_pipeline, cv=3, max_evals=20, scoring='roc_auc')
hyperopt_pipelines = hyperopt.fit(X_train, y_train)
100%|██████████| 20/20 [00:28<00:00, 1.43s/trial, best loss: -0.7890590689503734]
pipeline_model = hyperopt_pipelines.get_pipeline()
from sklearn.metrics import roc_auc_score
predicted_y = pipeline_model.predict(X_test)
score = roc_auc_score(predicted_y=='Risk', y_test=='Risk')
print(f'roc_auc_score {score:.1%}')
pipeline_model.visualize()
In this section you will learn how to deploy and score pipeline model as webservice using WML instance.
pipeline_name = "Pipeline_1"
from ibm_watson_machine_learning.deployment import WebService
service = WebService(wml_credentials, source_space_id=space_id)
service.create(
experiment_run_id=run_id,
model=pipeline_name,
deployment_name="Credit Risk Deployment AutoAI")
Preparing an AutoAI Deployment... Published model uid: e5c26fa2-98f4-485e-9e7f-6d0bb6f9a2ff Deploying model e5c26fa2-98f4-485e-9e7f-6d0bb6f9a2ff using V4 client. ####################################################################################### Synchronous deployment creation for uid: 'e5c26fa2-98f4-485e-9e7f-6d0bb6f9a2ff' started ####################################################################################### initializing...... ready ------------------------------------------------------------------------------------------------ Successfully finished deployment creation, deployment_uid='475d049a-32ee-4a5e-bb1b-85521e817bd8' ------------------------------------------------------------------------------------------------
Deployment object could be printed to show basic information:
print(service)
name: Credit Risk Deployment AutoAI, id: 475d049a-32ee-4a5e-bb1b-85521e817bd8, scoring_url: https://us-south.ml.cloud.ibm.com/ml/v4/deployments/475d049a-32ee-4a5e-bb1b-85521e817bd8/predictions, asset_id: e5c26fa2-98f4-485e-9e7f-6d0bb6f9a2ff
To show all available information about the deployment use the .get_params() method:
service.get_params()
{'entity': {'asset': {'id': 'e5c26fa2-98f4-485e-9e7f-6d0bb6f9a2ff'},
'custom': {},
'deployed_asset_type': 'model',
'hardware_spec': {'id': 'c076e82c-b2a7-4d20-9c0f-1f0c2fdf5a24',
'name': 'M',
'num_nodes': 1},
'hybrid_pipeline_hardware_specs': [{'hardware_spec': {'name': 'S',
'num_nodes': 1},
'node_runtime_id': 'auto_ai.kb'}],
'name': 'Credit Risk Deployment AutoAI',
'online': {},
'space_id': '2d463525-e69e-491b-b3bd-96f6d5562ce1',
'status': {'online_url': {'url': 'https://us-south.ml.cloud.ibm.com/ml/v4/deployments/475d049a-32ee-4a5e-bb1b-85521e817bd8/predictions'},
'state': 'ready'}},
'metadata': {'created_at': '2020-10-22T13:30:58.383Z',
'id': '475d049a-32ee-4a5e-bb1b-85521e817bd8',
'modified_at': '2020-10-22T13:30:58.383Z',
'name': 'Credit Risk Deployment AutoAI',
'owner': 'IBMid-55000091VC',
'space_id': '2d463525-e69e-491b-b3bd-96f6d5562ce1'}}
You can make scoring request by calling score() on deployed pipeline.
predictions = service.score(payload=train_df.drop(['Risk'], axis=1).iloc[:10])
predictions
{'predictions': [{'fields': ['prediction', 'probability'],
'values': [['No Risk', [0.9693139224748223, 0.03068607752517768]],
['No Risk', [0.9500418574643144, 0.04995814253568567]],
['No Risk', [0.9500710851398808, 0.049928914860119133]],
['No Risk', [0.9323351341779514, 0.06766486582204854]],
['Risk', [0.051245312146747546, 0.9487546878532525]],
['Risk', [0.016669384784646524, 0.9833306152153535]],
['No Risk', [0.8620795541590762, 0.1379204458409238]],
['No Risk', [0.9450837966345709, 0.05491620336542907]],
['No Risk', [0.9844135572973345, 0.015586442702665489]],
['Risk', [0.01756972756223618, 0.9824302724377638]]]}]}
If you want to work with the web service in an external Python application you can retrieve the service object by:
service = WebService(wml_credentials)service.list() methodservice.get('deployment_id') methodAfter that you can call service.score() method.
You can delete the existing deployment by calling the service.delete() command.
To list the existing web services you can use service.list().
A batch deployment processes input data from a inline data and return predictions in scoring details.
batch_payload_df = train_df.drop(['Risk'], axis=1)[:5] batch_payload_df
Copyright © 2020, 2021 IBM. This notebook and its source code are released under the terms of the MIT License.